package com.isd.global.util;


import com.isd.global.modelo.CorreoElectronico;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import com.isd.venta.modelo.Cliente;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JsfUtil {
    
    public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
        int size = selectOne ? entities.size() + 1 : entities.size();
        SelectItem[] items = new SelectItem[size];
        int i = 0;
        if (selectOne) {
            items[0] = new SelectItem("", "Seleccionar");
            i++;
        }
        for (Object x : entities) {
            items[i++] = new SelectItem(x, x.toString());
        }
        return items;
    }
    
    public static void ensureAddErrorMessage(Exception ex, String defaultMsg) {
        String msg = ex.getLocalizedMessage();
        if (msg != null && msg.length() > 0) {
            addErrorMessage(msg);
        } else {
            addErrorMessage(defaultMsg);
        }
    }
    
    public static void addErrorMessages(List<String> messages) {
        for (String message : messages) {
            addErrorMessage(message);
        }
    }

    public static void addErrorMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addErrorMessage(String tit,String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, tit, msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addInfoMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Información", msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addInfoMessage(String tit,String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, tit , msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addWarningMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Atención", msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addWarningMessage(String tit,String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, tit, msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addFatalMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error Fatal", msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addFatalMessage(String tit,String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, tit, msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }
    
    public static String getRequestParameter(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key);
    }
    
    public static Object getObjectFromRequestParameter(String requestParameterName, Converter converter, UIComponent component) {
        String theId = JsfUtil.getRequestParameter(requestParameterName);
        return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId);
    }
    
    public static <T> List<T> arrayToList(T[] arr) {
        if (arr == null) {
            return new ArrayList<T>();
        }
        return Arrays.asList(arr);
    }

    public static <T> Set<T> arrayToSet(T[] arr) {
        if (arr == null) {
            return new HashSet<T>();
        }
        return new HashSet(Arrays.asList(arr));
    }
    
    public static Object[] collectionToArray(Collection<?> c) {
        if (c == null) {
            return new Object[0];
        }
        return c.toArray();
    }

    public static <T> List<T> setToList(Set<T> set) {
        return new ArrayList<T>(set);
    }
    
    public static String getAsConvertedString(Object object, Converter converter) {
        return converter.getAsString(FacesContext.getCurrentInstance(), null, object);
    }
    
    public static String getCollectionAsString(Collection<?> collection) {
        if (collection == null || collection.size() == 0) {
            return "(No Items)";
        }
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (Object item : collection) {
            if (i > 0) {
                sb.append("<br />");
            }
            sb.append(item);
            i++;
        }
        return sb.toString();
    }

    public static Object getManagedBean(String bean){
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, bean);
    }

    public static Object getObjeto(String sBean,Class objeto){

       sBean = "#{"+sBean+"}";
       FacesContext context = FacesContext.getCurrentInstance();
       return context.getApplication().evaluateExpressionGet(context,sBean , objeto);

    }

    public static HttpSession getSession() {
        FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        return session;
    }

    public static Date getFecha(){
        
        try {
            Calendar c1 = GregorianCalendar.getInstance();
            String dia = String.valueOf(c1.get(Calendar.DAY_OF_MONTH));
            String mes = String.valueOf(c1.get(Calendar.MONTH)+1);
            String anio = String.valueOf(c1.get(Calendar.YEAR));

            SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            java.sql.Date fecFormatoDate = new java.sql.Date(sdf.parse(anio+"-"+mes+"-"+dia).getTime());

            return new Date(fecFormatoDate.getTime());

        } catch (ParseException ex) {            
            return new Date();
        }
    }

    public static String getCadenaAlfanumAleatoria (int longitud){
        String cadenaAleatoria = "";
        long milis = new java.util.GregorianCalendar().getTimeInMillis();
        Random r = new Random(milis);
        int i = 0;
        while ( i <= longitud){
            char c = (char)r.nextInt(255);
            if ( (c >= '0' && c <='9') || (c >='A' && c <='Z') ){
                cadenaAleatoria += c;
                i ++;
            }
        }
        return cadenaAleatoria;
    }

    public static String getMensajeClienteSinEmail(Cliente cliente){

        String mensaje = "El cliente ("+cliente.getNrocta()+") "+cliente.getNombre()+" ha confirmado un carrito en la tienda virtual pero no "
                        + "tiene cargado datos en dirección de e-mail, por lo tanto no puede recibir la notificación de confirmación de carrito \n\n"
                        + "Por favor, ingresarle una dirección de correo válida en el sistema ERP \n"
                        + "Muchas gracias\n"
                        + "Tienda Virtual Intercap S.R.L.";


        return mensaje;

    }
    
    public static CorreoElectronico getCorreoElectronicoClienteSinCorreo(Cliente cliente, String destinatario){

        try {

            String asunto  = "Cliente ("+cliente.getNrocta()+")"+ cliente.getNombre() + " sin correo electrónico ";
            String mensaje = "El cliente: ("+cliente.getNrocta()+")"+cliente.getNombre()+" \n";
            mensaje += "Ha intentado realizar operaciones en la tienda virtual, pero no tiene asociado ninguna cuenta de correo\n";
            mensaje += "Favor de ponerse en contacto con el cliente para actualizar los datos\n";

            CorreoElectronico ce = new CorreoElectronico(asunto, destinatario, mensaje);                        
            return ce;
            
        } catch (Exception e) {

            JsfUtil.addErrorMessage("No es posible generar el correo electrónico");
            return null;
        }
    }
}
